using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.DeviceClassificationDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.DeviceClassificationDictionaryHandler
{
    /// <summary>
    /// 删除器械分类处理器
    /// 处理器械分类逻辑删除请求，将指定器械分类标记为已删除状态
    /// </summary>
    public class DeleteApparatusTypeHandler : IRequestHandler<DeleteApparatusTypeCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<ApparatusType> _apparatusTypeRepository;
        private readonly ILogger<DeleteApparatusTypeHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="apparatusTypeRepository">仓储</param>
        /// <param name="logger">日志记录器</param>
        public DeleteApparatusTypeHandler(
            IBaseRepository<ApparatusType> apparatusTypeRepository,
            ILogger<DeleteApparatusTypeHandler> logger)
        {
            _apparatusTypeRepository = apparatusTypeRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除器械分类请求
        /// </summary>
        /// <param name="request">删除器械分类命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public Task<ApiResult<bool>> Handle(DeleteApparatusTypeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID查找器械分类记录
                var apparatusType = _apparatusTypeRepository.GetModel(request.Id);
                if (apparatusType == null)
                {
                    return Task.FromResult(new ApiResult<bool>
                    {
                        Code = ApiEnums.NotFound,
                        Msg = "器械分类不存在",
                        Data = false
                    });
                }

                // 执行逻辑删除：将IsDeleted设为true
                apparatusType.IsDeleted = true;
                apparatusType.UpdateTime = DateTime.Now;

                var result = _apparatusTypeRepository.Update(apparatusType) > 0;

                return Task.FromResult(new ApiResult<bool>
                {
                    Code = result ? ApiEnums.Success : ApiEnums.Error,
                    Msg = result ? "器械分类删除成功" : "器械分类删除失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除器械分类时发生异常");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Error,
                    Msg = "删除器械分类时发生错误",
                    Data = false
                });
            }
        }
    }
}